package com.saris.primego.config.mapping;

import com.saris.primego.pojo.entity.Dish;
import com.saris.primego.pojo.vo.DishVO;
import com.saris.primego.service.CategoryService;
import jakarta.annotation.PostConstruct;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
public class DishMappingConfig {
    private final CategoryService categoryService;
    private final ModelMapper modelMapper;

    public DishMappingConfig(CategoryService categoryService,@Lazy ModelMapper modelMapper) {
        this.categoryService = categoryService;
        this.modelMapper = modelMapper;
    }

    @PostConstruct  // 在 Bean 初始化后自动执行
    public void configureDishMappings() {
        // 定义转换器
        Converter<Long, String> categoryConverter = ctx ->
                categoryService.getCategoryNameById(ctx.getSource());

        // 配置 Dish → DishVO 的映射
        modelMapper.createTypeMap(Dish.class, DishVO.class)
                .addMappings(mapper -> {
                    mapper.using(categoryConverter)
                            .map(Dish::getCategoryId, DishVO::setCategoryName);
                });
    }
}
